package falcon.server.processor;

import falcon.common.Errno;
import falcon.common.FalconConfig;
import falcon.common.FalconUser;
import falcon.server.FalconByteBufHandler;
import falcon.server.FalconProManager;

public final class FalconSysProcessor {

	public static void processLogin(FalconProManager manager, FalconProManager.Req req, String[] pa) {
		FalconByteBufHandler handler = req.handler;
		if (handler.isLogin()) {
			req.errno = Errno.VERIF_REPEAT_LOGIN;
			req.desc = "重复登陆";
			return;
		}
		if (pa.length < 2) {
			req.errno = Errno.COM_ARGS_MISS;
			req.desc = "登陆参数异常";
			return;
		}
		FalconConfig config = manager.getConfig();
		String clientHost = handler.getClientHost();
		int clientPort = handler.getClientPort();
		String loginUser = pa[0];
		String password = pa[1];
		int errno = FalconUser.check(config, loginUser, password, clientHost);
		if (errno != Errno.SUCCESS) {
			req.errno = errno;
			req.desc = "登陆失败";
			return;
		}
		handler.setUser(loginUser);
		manager.updateSession(clientHost, clientPort, loginUser, handler);
	}
	
	public static void processLogout(FalconProManager manager, FalconProManager.Req req, String[] pa) {
		if (pa.length != 1) {
			req.errno = Errno.COM_ARGS_INVALID;
			req.desc = "参数: pa.length != 1";
			return;
		}
		FalconByteBufHandler handler = req.handler;
		String loginUser = pa[0];
		if (!loginUser.equals(handler.getUser())) {
			req.errno = Errno.COM_NOT_FOUND;
			req.desc = "注销用户不存在";
			return;
		}
		handler.setUser(null);
		req.errno = Errno.VERIF_LOGOUT;
		req.desc = "注销成功";
	}
}
